package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.contract.model.entity.WarehouseContract;
import com.wing.contract.model.entity.WarehouseContractFee;
import com.wing.contract.model.entity.WarehouseContractProduct;
import com.wing.contract.model.request.WarehouseContractForm;
import com.wing.contract.service.WarehouseContractFeeService;
import com.wing.contract.service.WarehouseContractProductService;
import com.wing.product.dao.WarehouseSettledDao;
import com.wing.product.model.entity.WarehouseSettledEntity;
import com.wing.product.model.request.WarehouseSettledForm;
import com.wing.product.model.response.WarehouseSettledContractVO;
import com.wing.product.model.response.WarehouseSettledVO;
import com.wing.product.model.response.WarehouseShipmentOrderVO;
import com.wing.user.model.entity.SelContactInfo;
import com.wing.user.service.SelContactInfoService;
import com.wing.user.service.WarehouseContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WarehouseSettledServiceImpl extends ServiceImpl<WarehouseSettledDao, WarehouseSettledEntity>
        implements WarehouseSettledService{
    @Autowired
    private WarehouseContractService warehouseContractService;

    @Autowired
    private WarehouseContractProductService warehouseContractProductService;

    @Autowired
    private WarehouseContractFeeService warehouseContractFeeService;

    @Autowired
    private WarehouseSettledDao warehouseSettledDao;

    @Autowired
    private SelContactInfoService selContactInfoService;

    @Override
    public Page<WarehouseSettledVO> pageList4app(Page page, Map<String, Object> params) {
        List<WarehouseSettledVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public boolean save(WarehouseSettledForm warehouseSettledForm) throws ParseException {
        //判断申请时间是否在生效日期内
        SelContactInfo selContactInfo =selContactInfoService.getById(warehouseSettledForm.getContactId());
        List<WarehouseContract> warehouseContract=warehouseContractService.findByCustomerId(selContactInfo.getSelCustomerId());
        for (int i = 0; i < warehouseContract.size(); i++) {
            if(null==warehouseContract.get(i).getEffectiveDate() || null==warehouseContract.get(i).getExpiryDate() || null==warehouseContract.get(i).getWarehouseId()){
                continue;
            }
            if(checkTime(warehouseContract.get(i).getEffectiveDate().toString(),warehouseContract.get(i).getExpiryDate().toString())==true && warehouseContract.get(i).getWarehouseId().equals(warehouseSettledForm.getFactoryId())){

                return false;
            }
        }

        WarehouseSettledEntity warehouseSettledEntity = new WarehouseSettledEntity();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WarehouseSettledEntity.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseSettledForm, warehouseSettledEntity,copyOptions);
        warehouseSettledEntity.setStatus(0);
        warehouseSettledEntity.setRemark(warehouseSettledForm.getRemark());
        warehouseSettledEntity.setSettledOrder(UniqueIdGeneratorUtil.generateUniqueId("RZ", "yyyyMMddHHmmss", 1000, 9999));
        baseMapper.insert(warehouseSettledEntity);
        return true;
    }

    @Override
    @Transactional
    public boolean examine(WarehouseContractForm warehouseContractForm) {
        WarehouseSettledEntity warehouseSettledEntity=this.baseMapper.selectByIdWithoutVersion(warehouseContractForm.getSettledId());
        //新增一条合同
        WarehouseContract warehouseContract = new WarehouseContract();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WarehouseContract.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseContractForm, warehouseContract,copyOptions);
        warehouseContract.setContractor(warehouseContractForm.getContractorId());
        warehouseContract.setWarehouseId(Long.parseLong(warehouseSettledEntity.getFactoryId()));
        warehouseContract.setContactId(warehouseContractForm.getContactId());
        warehouseContract.setContractCode(UniqueIdGeneratorUtil.generateUniqueId("TGHT", "yyyyMMddHHmmss", 1000, 9999));
        warehouseContract.setWarehouseCustomerId(warehouseContractForm.getWarehouseCustomerId());
//        warehouseContract.setWarehouseCustomerId(warehouseContractForm.getWarehouseCustomerId());
        warehouseContractService.save(warehouseContract);
        //修改入驻申请的审核状态

        warehouseSettledEntity.setStatus(warehouseContractForm.getSettledStatus());
        warehouseSettledEntity.setTrusteeshipContractId(String.valueOf(warehouseContract.getId()));
        baseMapper.updateById(warehouseSettledEntity);
        //新增服务项的关联记录
        for (int i = 0; i < warehouseContractForm.getWarehouseFeeItemsList().size(); i++) {
            WarehouseContractFee warehouseContractFee=new WarehouseContractFee();
            warehouseContractFee.setContractId(warehouseContract.getId());
            warehouseContractFee.setContractPrice(Double.parseDouble(warehouseContractForm.getWarehouseFeeItemsList().get(i).getPrice().toString()));
            warehouseContractFee.setMemberPrice(Double.parseDouble(warehouseContractForm.getWarehouseFeeItemsList().get(i).getPrice().toString()));
            warehouseContractFee.setProductFeeId(warehouseContractForm.getWarehouseFeeItemsList().get(i).getId());
            warehouseContractFeeService.save(warehouseContractFee);
        }

        //新增托管单价关联记录（牌号，钢种）
        for (int i = 0; i < warehouseContractForm.getWarehouseProductVarietyList().size(); i++) {
            WarehouseContractProduct warehouseContractProduct = new WarehouseContractProduct();
            warehouseContractProduct.setContractId(warehouseContract.getId());
            warehouseContractProduct.setContractPrice(warehouseContractForm.getWarehouseProductVarietyList().get(i).getContractPrice());
            warehouseContractProduct.setMemberPrice(warehouseContractForm.getWarehouseProductVarietyList().get(i).getMemberPrice());
            warehouseContractProduct.setProductVarietyId(warehouseContractForm.getWarehouseProductVarietyList().get(i).getId());
            warehouseContractProductService.save(warehouseContractProduct);
        }
        return true;
    }

    @Override
    public JsonResult updateStatus(Long id, Integer status){
        baseMapper.updateStatus(id,status);
//        WarehouseSettledEntity warehouseSettledEntity =baseMapper.selectById(id);
//        warehouseSettledEntity.setStatus(status);
//        baseMapper.updateById(warehouseSettledEntity);
        return JsonResult.success("操作成功");
    }

    @Override
    public WarehouseSettledContractVO info(Long id) {
        WarehouseSettledContractVO warehouseSettledContractVO=warehouseSettledDao.findByContactId(id);
        if(null!=warehouseSettledContractVO.getTrusteeshipContractId()){
            warehouseSettledContractVO.setWarehouseContractFeeVOList(warehouseSettledDao.findFeeByContactId(Long.parseLong(warehouseSettledContractVO.getTrusteeshipContractId())));
            warehouseSettledContractVO.setWarehouseContractProductVOList(warehouseSettledDao.findVarietyByContactId(Long.parseLong(warehouseSettledContractVO.getTrusteeshipContractId())));
        }
         return warehouseSettledContractVO;
    }

    @Override
    public List<WarehouseSettledEntity> findAllContactByFactoryId(String factoryId,Long warehouseCustomerId) {
        return warehouseSettledDao.findAllContactByFactoryId(factoryId, warehouseCustomerId);
    }

    //判断某个日期是否在两个日期范围之内
    public boolean checkTime(String startTime,String endTime) throws ParseException {
        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd");
        Date date1=simpleDateFormat.parse(startTime);
        Date date2=simpleDateFormat.parse(endTime);
        Date date3=new Date();
        if(date1.getTime()<=date3.getTime() && date2.getTime()>=date3.getTime()){
            System.out.println("日期范围内！");
            return true;
        }else{
            return false;
        }

    }
}
